package cn.wolfcode.web.interceptor;

import cn.wolfcode.JWTUtils;
import cn.wolfcode.domain.Result;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JWTUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        /**
//         * 是否有token
//         * token是否能解析
//         */
//        String token = request.getHeader("token");
//        log.info("从头部取出的token{}",token);
//        if (StringUtils.isEmpty(token)){
//            log.info("token 不存在");
//
////            response.setContentType("application/json;charset=utf-8");
////            Result not_login = Result.error("NOT_LOGIN");
////            String s = JSONObject.toJSONString(not_login);
////            response.getWriter().println(s);
////            return false;
//            throw new LoginException("");
//        }
//
//        try {
//            jwtUtils.parserJWT(token);
//            return true;
//        } catch (Exception e) {
////            response.setContentType("application/json;charset=utf-8");
////            Result not_login = Result.error("NOT_LOGIN");
////            String s = JSONObject.toJSONString(not_login);
////            response.getWriter().println(s);
//            throw new LoginException("");
////            e.printStackTrace();
//
//        }
////        System.out.println("拦截器生效");
////        return false;


        try {
            jwtUtils.parserJWT(request.getHeader("token"));
            return true;
        } catch (Exception e) {
            response.setContentType("application/json;charset=utf-8");
            Result not_login = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(not_login);
            response.getWriter().println(s);
            e.printStackTrace();
            return false;
        }


    }


}
